package com.huitone.smspfm.interfacz.tasks;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.data.redis.connection.RedisConnection;

import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.context.utils.ContextUtils;
import com.huitone.smspfm.interfacz.core.AppStaticConfigs;
import com.huitone.smspfm.interfacz.dao.BlackUserMapper;
import com.huitone.smspfm.interfacz.dao.SmsResultCodeDefMapper;
import com.huitone.smspfm.interfacz.dao.SmsSendRecordMapper;
import com.huitone.smspfm.interfacz.dao.entity.BlackUser;
import com.huitone.smspfm.interfacz.dao.entity.BlackUserExample;
import com.huitone.smspfm.interfacz.dao.entity.SmsResultCodeDef;
import com.huitone.smspfm.interfacz.dao.entity.SmsResultCodeDefExample;
import com.huitone.smspfm.interfacz.dao.entity.SmsSendRecord;
import com.huitone.smspfm.interfacz.dao.entity.SmsSendRecordExample;
import com.huitone.smspfm.interfacz.logger.ExtLogger;
import com.huitone.smspfm.redis.pipeline.PipelineOpts.ABExcuteCommands;

public class AutoMaticBlackListTask extends Thread {
	
	private static final ExtLogger logger = ExtLogger.create(AutoMaticBlackListTask.class);
	
	private static String BLACK_LIST_CODE_TYPE = "1";

	private boolean keepGoing = true;
	
	private long sleepTime = 10*60*1000L;
	
	private Date currDate = new Date();
	
	public boolean isKeepGoing() {
		return keepGoing;
	}

	public void setKeepGoing(boolean keepGoing) {
		this.keepGoing = keepGoing;
	}

	@Override
	public void run() {
		while(keepGoing && ! this.isInterrupted()){
			try{
				if(AppStaticConfigs.smsBlackAutoMaticOnOff){
					logger.info("启动黑名单识别任务");
					scanRecordAndSaveBlackUser();
				}
				
				
			} catch (Exception e){ e.printStackTrace(); }
			
			try {	Thread.sleep(sleepTime);} catch (InterruptedException e) {	e.printStackTrace();}
		}
		
		logger.info("自动检测并添加至黑名单用户任务　已成功退出！");
	}

	private void scanRecordAndSaveBlackUser() {
		//１.扫描短信接收记录表产生黑名单用户
		Calendar  cal = Calendar.getInstance();
		cal.add(Calendar.MINUTE,-10);//数据库有延时，延后10分钟保证数据的完整性
		Date tempDate = cal.getTime();
		cal.add(Calendar.HOUR, -3);
		Date recvTime = cal.getTime();
		Set<String> backListUser = new HashSet<String>();
		SmsSendRecordExample  example = new SmsSendRecordExample();
		example.createCriteria().andInsertTimeBetween(currDate, tempDate)
			.andRecvTimeBetween(recvTime, tempDate)
			.andSendCodeIsNotNull().andSendCodeNotEqualTo("0");//发送失败的记录
		SmsSendRecordMapper smsSendRecordMapper = ContextUtils.getBean2(SmsSendRecordMapper.class);
		List<SmsSendRecord> smsSendRecordS = smsSendRecordMapper.selectByExample(example);
		
		currDate = tempDate;
		if( ! StringUtils.isEmpty(smsSendRecordS) && smsSendRecordS.size() > 0){
			Set<SmsResultCodeDef> smsResultCodeDefLists = AppStaticConfigs.smsResultCodeDefMap.get(BLACK_LIST_CODE_TYPE);
			Set<String> backList = new HashSet<String>();
			for(SmsResultCodeDef srcd : smsResultCodeDefLists){
				String value = srcd.getGateType()+":"+srcd.getCodeContent();
				if(! StringUtils.isEmpty(value)){
					backList.add(value.toUpperCase());
				}
			}
			for(int i = 0; i < smsSendRecordS.size() ; i++){
				SmsSendRecord smsRecord = smsSendRecordS.get(i);
				String gateLinkId = smsRecord.getGateLinkId();
				String gateType = null;
				if(! StringUtils.isEmpty(gateLinkId)){
					gateType = AppStaticConfigs.gateTypeMap.get(gateLinkId);
				}
				
				String resultCode = smsRecord.getResultCode();
				if( backList.contains((gateType + ":"+ resultCode).toUpperCase())){//加入黑名单中
					backListUser.add(smsRecord.getUserNo());
				}
				
			}
		}
		//2.保存黑名单用户
		if (backListUser.size() > 0) {
			// TODO
			AppStaticConfigs.pipelineOpts2.save(new ABExcuteCommands() {
				@Override
				public void excute(RedisConnection connection) {
					BlackUserMapper mapper = ContextUtils
							.getBean2(BlackUserMapper.class);
					Date dateTmp = new Date();
					long score = System.currentTimeMillis();
					for (String userNo : backListUser) {
						BlackUser blackUser = new BlackUser();
						blackUser.setInsertTime(dateTmp);
						blackUser.setLastModTime(dateTmp);
						blackUser.setBlackUser(userNo);
						blackUser.setDesc("system auto add");
						blackUser.setStatus("1");
						blackUser.setInsertStaffId("system");
						blackUser.setLastModStaffId("system");
						blackUser.setSource("1");

						mapper.insertNoRecId(blackUser);
						logger.info("自动检测加入黑名单中: " + userNo);

						// TODO 加入黑名单缓存中
						
						StringBuffer buffer = new StringBuffer();
						buffer.setLength(0);
//								buffer.append(StringUtils.toString(buser.getSvrNode()));
						buffer.append(":");
//								buffer.append(StringUtils.toString(buser.getServiceCode()));
						buffer.append(":");
						buffer.append(StringUtils.phNumRem86(StringUtils.toString(blackUser.getBlackUser())));
						connection.zAdd(AppStaticConfigs.configBlackListZSetB, score, AppStaticConfigs.stringRedisSerializer.serialize(buffer.toString()));
					}

				}
			});

		}
	}

	@Override
	public void destroy() {
		this.setKeepGoing(false);
		this.interrupt();
	}
	
	

}
